package gen.tools.delivery;

import gen.tools.Widgets;
import gen.tools.structures.InfoStruc;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class QuerySubsysSquad extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public QuerySubsysSquad() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( wid.UIcodeSet );		
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		
		final String subsysId = request.getParameter("subsysId");
		final String fileDepType = request.getParameter("fileDepType");
		
		/*	預設的SQL語句是for non-web的	*/ 
		String sql = "SELECT t1.squadpath,t1.squadid,t1.subsysid,t1.squadname,t2.subsysDesc FROM squad t1,subsyses t2 WHERE t1.subsysid=t2.subsysid";
		
		/*	如果是web的，SQL語句就要改查 squalGroup了	*/
		if ( "w".equalsIgnoreCase( fileDepType ) ) {	
			sql = "SELECT t1.sqgruseqid, t1.subsysid,t1.sqgruseqname,t2.subsysDesc FROM squadgroup t1,subsyses t2 WHERE t1.subsysid=t2.subsysid";
		}
		
		if (!"".equalsIgnoreCase(subsysId)) {
			sql += " AND t1.subsysid='"+subsysId+"'"; 
		}
		
		final ArrayList<InfoStruc> infoStrucs = new ArrayList<InfoStruc>();
		
		try {
			conn = wid.getConn();	
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				final InfoStruc infoStruc = new InfoStruc();
				infoStruc.setId( rs.getString("subsysDesc") +" ("+rs.getString("subsysid")+")");	//借用ID為子系統
				if ( "n".equalsIgnoreCase( fileDepType ) ) {	
					infoStruc.setName( rs.getString("squadname")+" ("+rs.getString("squadid")+")");	//借用Name為Squad
					infoStruc.setSquadPath( rs.getString("squadpath")  );
				} else {
					infoStruc.setName( rs.getString("sqgruseqname")+" ("+rs.getString("sqgruseqid")+")");	//借用Name為squadGroup
					
				}
				
				infoStrucs.add(infoStruc);
			}
		} catch ( Exception e) {
			wid.errLog(e);
		} finally {
			try {
				if (rs != null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				System.out.println(wid.errProcess(e));
			}
		}
		response.getWriter().write(new Gson().toJson(infoStrucs));
	
	}

}
